package com.zwps.biz.controller.listener.rabbitmq;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.zwps.biz.api.model.dto.mointordentify.AlarmBroacdCastVO;
import com.zwps.biz.api.model.dto.mointordentify.AlarmMessageDTO;

import com.zwps.biz.api.model.dto.mointordentify.PictureMessageDTO;

import com.zwps.biz.controller.config.JacksonConfig;
import com.zwps.biz.dal.db.object.AlarmBroadcastDO;
import com.zwps.biz.domain.service.AlarmBroadcastService;
import com.zwps.biz.domain.service.MonitorAlarmRecordService;
import com.zwps.biz.domain.service.PictureRsvrService;
import com.zwps.biz.domain.service.impl.ApiService;
import com.zwps.common.cache.CacheService;
import com.zwps.common.core.context.RabbitmqDefine;
import com.zwps.common.core.enums.MessageTypeEnum;
import com.zwps.common.core.service.LogService;
import lombok.AllArgsConstructor;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;



/**
 * 监控视频告警数据消费
 */
@Component
@ConditionalOnProperty("spring.rabbitmq.enable")
@AllArgsConstructor
public class MonitorAlarmMQListener  {


    @Autowired
    private MonitorAlarmRecordService  service;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private PictureRsvrService  pictureRsvrService;

    @Autowired
    private AlarmBroadcastService broadcastService;



/*

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitmqDefine.LHK_MONITOR_ALARM_MESSAGE_QUEUE, durable = "false"), // 配置队列rtcd.detect_alarm
            exchange = @Exchange(value = RabbitmqDefine.LHK_MONITOR_ALARM_EXCHANGE_NAME, type = TOPIC), // 配置交换机，交换机类型 mshub.nfnh
            key = { RabbitmqDefine.LHK_MONITOR_ALARM_MESSAGE_ROUTE } // 配置路由rtcd.detect_alarm
    ), ackMode = "MANUAL")
    public void messageLogListener(Channel channel, Message message) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        logService.consumeRecord((body,logMessage)->{
            AlarmMessageDTO alarmMessageDTO = objectMapper.readValue(message.getBody(), AlarmMessageDTO.class);
        service.addRecordInit(alarmMessageDTO);
        },message, MessageTypeEnum.RECOGNIZE_LISTEN_ALARM_SAMPLE_SYNC);
    }


    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitmqDefine.DETECT_PICTURE_MESSAGE_QUEUE, durable = "false"), // 配置队列rtcd.detect_alarm
            exchange = @Exchange(value = RabbitmqDefine.LHK_DETECT_PICTURE_EXCHANGE_NAME, type = TOPIC), // 配置交换机，交换机类型 mshub.nfnh
            key = { RabbitmqDefine.DETECT_PICTURE_MESSAGE_ROUTE }
    ), ackMode = "MANUAL")
    public void messagePictureListener(Channel channel, Message message) throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        logService.consumeRecord((body,logMessage)->{
            PictureMessageDTO pictureMessageDTO = objectMapper.readValue(message.getBody(), PictureMessageDTO.class);
            pictureRsvrService.addPictureRsvr(pictureMessageDTO);
        },message, MessageTypeEnum.RECOGNIZE_LISTEN_ALARM_SAMPLE_SYNC);
    }

    *//**
     * 视频广播告警
     * @param channel
     * @param message
     * @throws IOException
     *//*
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitmqDefine.LHK_BROADCAST_ALARM_QUEUE, durable = "false"), // 配置队列rtcd.detect_alarm
            exchange = @Exchange(value = RabbitmqDefine.LHK_BROADCAST_ALARM_EXCHANGE_NAME, type = TOPIC), // 配置交换机，交换机类型 mshub.nfnh
            key = { RabbitmqDefine.LHK_BROADCAST_ALARM_ROUTKEY } // 配置路由rtcd.detect_alarm
    ), ackMode = "MANUAL")
    public void broadCastListener(Channel channel, Message message) throws IOException {

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        logService.consumeRecord((body,logMessage)->{
            AlarmBroacdCastVO alarmMessageBroacdCastVO = objectMapper.readValue(message.getBody(), AlarmBroacdCastVO.class);
            AlarmBroadcastDO broadcastDO = new AlarmBroadcastDO();
            BeanUtils.copyProperties(alarmMessageBroacdCastVO,broadcastDO);
            broadcastDO.setImgsUrl(alarmMessageBroacdCastVO.getImgsUrl().toString().replaceAll("[\\[\\]]", ""));
            broadcastService.save(broadcastDO);
        },message, MessageTypeEnum.RECOGNIZE_LISTEN_ALARM_SAMPLE_SYNC);
    }


    private Object convertItemToInteger(Object item) {
        if (item instanceof String) {
            return convertStringToInteger((String) item);
        } else if (item instanceof Integer) {
            return item; // 已经是Integer，直接返回
        }
        // 其他类型可以根据需求处理或返回null
        return null;
    }

    private Integer convertStringToInteger(String str) {
        if (str == null || str.trim().isEmpty()) {
            return null;
        }

        try {
            // 获取下划线前的部分
            String numberStr = str;
            int underscoreIndex = str.indexOf('_');
            if (underscoreIndex > 0) {
                numberStr = str.substring(0, underscoreIndex);
            }

            return Integer.parseInt(numberStr.trim());
        } catch (NumberFormatException e) {
            System.err.println("字符串转换Integer失败: " + str);
            return null;
        }
    }

    public void getAlarm() {
        try {
            HttpRequest request = HttpUtil
                    .createPost("http://10.34.186.153:40037" + "/api/rt/picture/detect");
            request.timeout(10000);
            request.body("{\n" +
                    "  \"source\": \"https://img0.baidu.com/it/u=2632050946,2025523379&fm=253&fmt=auto&app=138&f=JPEG?w=818&h=500\",\n" +
                    "  \"tid\": \"test\",\n" +
                    "  \"mode\": 1,\n" +
                    "  \"app\": \"com\"\n" +
                    "}");

            String response = request.execute().body();
            System.out.println("响应：" + response);
        }catch (Exception e){
            System.out.println("请求失败！");
        }



    }*/


}
